package com.liry.mybatis.datascope.model;

import com.liry.mybatis.datascope.annotation.DataColumn;
import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * 数据权限 - 字段权限对象
 *
 * @author ALI
 * @since 2022/9/13
 */
@Data
@EqualsAndHashCode
public class DataColumnProperty {
    /**
     * 表别名
     */
    private String alias;
    /**
     * 字段名称
     */
    private String name;

    /**
     * 比较类型
     */
    private String operator;
    /**
     * 字段值
     */
    private Object value;

    public DataColumnProperty() {

    }

    public DataColumnProperty(String alias, String name) {
        this.alias = alias;
        this.name = name;
    }

    public DataColumnProperty(String alias, String name, String value) {
        this.alias = alias;
        this.name = name;
        this.value = value;
    }

    public static DataColumnProperty from(DataColumn data) {
        DataColumnProperty result = new DataColumnProperty();
        result.setAlias(data.alias());
        result.setName(data.name());
        result.setOperator(data.operator());
        result.setValue(data.value());
        return result;
    }

    public String getAliasDotName() {
        return isWhitespace(this.alias) ? this.name : this.alias + "." + this.name;
    }

    /**
     * 使用别名
     *
     * @param useAlias 表别名
     */
    public String getAliasDotName(boolean useAlias) {
        if (useAlias) {
            // 默认使用主表
            this.alias = "t";
        }
        return !useAlias ? this.name : this.alias + "." + this.name;
    }

    private boolean isWhitespace(String name) {
        if (this.alias == null || this.alias.length() == 0) {
            return true;
        }
        for (int var2 = 0; var2 < this.alias.length(); ++var2) {
            if (!Character.isWhitespace(this.alias.charAt(var2))) {
                return false;
            }
        }
        return true;
    }
}